<?php
/**
 * 角色控制器
 * User: xuyiping(xuyiping@liangzihuzhu.com.cn)
 * Date: 2017/11/27
 * Time: 17:06
 */

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Model\User\PermissionModel;
use App\Model\User\PermissionGroupModel;
use App\Model\User\RoleGroupModel;
use App\Model\User\RoleModel;
use App\Model\User\RolePermissionModel;
use App\Model\User\UserRoleModel;
use Illuminate\Http\Request;


class RoleController extends Controller{

    //打开角色组列表
    public function index(){

        $role_group = RoleGroupModel::all()->toArray();
        $data = [
            'roleGroup' => json_encode($role_group),
            'user_roleGroup_data' => $role_group
        ];

        return view('Admin/system/role/index',$data);
    }

    public function search(Request $request){

        $where = [];

        //查询条件
        if ($request->input('roleName')) {
            $where['roleName'] = $request->input('roleName');
        }

        if ($request->input('roleGroupID')) {
            $where['roleGroupID'] = $request->input('roleGroupID');
        }

        $groups = RoleModel::where($where)
            ->orderBy($request->input('sort'), $request->input('order'))
            ->paginate($request->input('limit'))
            ->toArray();

        //返回数组
        $res_data = array(
            'total' => $groups['total'],
            'rows' => array()
        );

        foreach ( $groups['data'] as &$row ) {

            $operation = '<a href="javascript: void(0);" onclick="Role.del(' . $row['roleID'] . ');">删除</a>&nbsp&nbsp';
            $operation .= '<a href="javascript: void(0);" onclick="Role.edit(' . $row['roleID'] . ');">修改</a>&nbsp&nbsp';
            $operation .= '<a href="javascript: void(0);" onclick="Role.permission(' . $row['roleID'] . ');">权限</a>&nbsp&nbsp';

            $res_data['rows'][] = array(
                'operation' => $operation,
                'roleName' => $row['roleName'],
                'roleGroupName' => $row['roleGroupName'],
                'memo' => $row['memo'],
            );
        }

        return response()->json($res_data);

    }

    public function permission($id){

        //角色权限单维数组
        $role_permission = RolePermissionModel::where('roleID', $id);
        if ($role_permission) {
            $role_permission = $role_permission->pluck('permissionID')->toArray();
        } else {
            $role_permission = [];
        }
        //权限组数据
        $permission_group = PermissionGroupModel::select('group_id','group_name')->get()->toArray();

        if ($permission_group) {

            foreach ($permission_group as $key => &$group) {

                $group['selected'] = 1;

                //权限数据
                $permission = PermissionModel::select('permissionID', 'permissionName')
                    ->where('permissionGroupID', $group['group_id'])
                    ->get();

                if (!$permission) {
                    unset($permission_group[$key]);
                    break;
                }

                foreach($permission as $p) {

                    if (in_array($p->permissionID, $role_permission)) {
                        $checked = 1;
                    } else {
                        $checked = 0;
                        $group['selected'] = 0;
                    }

                    $group['list'][] = [
                        'permissionID' => $p->permissionID,
                        'permissionName' => $p->permissionName,
                        'checked' => $checked
                    ];

                }

            }

        }

        $data = [
            'permissionGroup' => $permission_group,
            'roleID' => $id
        ];

        return  view('Admin/system/role/rolepermission', $data);
    }

    public function storePermission(Request $request){
        $id = $request->input('id');
        $permission = $request->input('permission');

        if(empty($id)){
            return response()->json(['code'=>1001,'message'=>'角色参数错误']);
        }

        if(empty($permission)){
            return response()->json(['code'=>1002,'message'=>'请选择权限']);
        }

        //查询角色是否存在
        $role = RoleModel::select('RoleID')->find($id);
        if(!$role){
            return response()->json(['code'=>1003,'message'=>'角色信息没有找到']);
        }

        //删除角色已有的权限
        RolePermissionModel::where('roleID',$id)->delete();

        $userId = session('ADMIN_USER_ID');
        foreach ($permission as $value){

            if(!is_numeric($value)){
                continue;
            }

            //检查权限信息是否存在
            $permission_obj = PermissionModel::find($value);
            if (!$permission_obj) {
                continue;
            }

            RolePermissionModel::create([
                'uuid' => makeUuid(),
                'timeStamp' =>date('Y-m-d H:i:s'),
                'createTime' =>date('Y-m-d H:i:s'),
                'creator' => $userId,
                'roleID' => $id,
                'permissionGroupID' => $permission_obj->permissionGroupID,
                'permissionID' => $value
            ]);

        }
        return response()->json([
            'code' => 200,
            'message' => 'ok'
        ]);

    }

    public function get($id){
        $role = RoleModel::select('roleID', 'roleName', 'memo','roleGroupID')->find($id);

        if ($role) {
            return response()->json([
                'code' => 200,
                'message' => 'ok',
                'data' => $role
            ]);
        } else {
            return response()->json([
                'code' => 404,
                'message' => '角色信息没有找到'
            ]);
        }
    }

    public function delete($id){
        //判断是否有用户
        if($userrole = UserRoleModel::where('roleID',$id)->first()){
            return response()->json(['code' => 1000001, 'message' => '该角色下有用户，请先处理用户']);
        }
        //判断是否是系统管理员
        $role = RoleModel::where('roleID',$id)->first();
        if( $role && $role->roleGroupID == 1){
            return response()->json(['code' => 1000002, 'message' => '不能删除系统管理员!']);
        }

        $role->delete();
        return response()->json([
            'code' => 200,
            'message' => 'ok'
        ]);
    }

    public function store(Request $request){
        $msg = '';
        //验证单子
        if(empty($request->input('roleName'))){
            $msg .= '角色名称没有填写';
        }

        if(empty($request->input('roleGroupName'))){
            $msg .= '没有选择角色组';
        }
        if($msg){
            return response()->json([
                'code' => 400,
                'message' => $msg
            ]);
        }

        //新增或修改角色信息
        if ( $id = $request->input('roleID') ) {
            $role = RoleModel::find($request->input('roleID'));
        } else {
            if( $check_data = RoleModel::where('roleName', $request->input('roleName') )->first() ){
                return response()->json([
                    'code' => 200,
                    'message' => '数据已存在'
                ]);
            }else{
                $role = new RoleModel();

                $role->uuid = makeUuid();
                $role->timeStamp = date('Y-m-d H:i:s');
                $role->createTime = date('Y-m-d H:i:s');
                $role->creator = session('ADMIN_USER_ID');
            }
        }
        $role->roleName = $request->input('roleName');
        $role->roleGroupID = $request->input('roleGroupID');
        $role->roleGroupName = $request->input('roleGroupName');
        $role->memo = $request->input('memo');

        $role->save();

        return response()->json([
            'code' => 200,
            'message' => 'ok'
        ]);

    }

}